const Medicine = require('../models/medicine.model');
const schedule = require('node-schedule');

class MedicineStatusService {
  // 更新单个药品的状态
  static async updateMedicineStatus(medicine) {
    const now = new Date();
    const expiryDate = new Date(medicine.expiryDate);
    const thirtyDaysFromNow = new Date(now.getTime() + (30 * 24 * 60 * 60 * 1000));

    let status = 'normal';
    if (expiryDate < now) {
      status = 'expired';
    } else if (expiryDate <= thirtyDaysFromNow) {
      status = 'nearExpiry';
    }

    if (medicine.status !== status) {
      await Medicine.findByIdAndUpdate(medicine._id, { status });
      // TODO: 通过WebSocket发送状态更新通知
      return true;
    }
    return false;
  }

  // 批量更新所有药品状态
  static async updateAllMedicineStatus() {
    try {
      const medicines = await Medicine.find();
      const updates = await Promise.all(
        medicines.map(medicine => this.updateMedicineStatus(medicine))
      );
      const updatedCount = updates.filter(Boolean).length;
      console.log(`已更新${updatedCount}个药品的状态`);
    } catch (error) {
      console.error('更新药品状态时出错:', error);
    }
  }

  // 启动定时任务
  static startStatusUpdateJob() {
    // 每天凌晨2点执行状态更新
    schedule.scheduleJob('0 2 * * *', async () => {
      console.log('开始执行药品状态更新任务...');
      await this.updateAllMedicineStatus();
    });
    console.log('药品状态更新定时任务已启动');
  }
}

module.exports = MedicineStatusService;